package com.cefa.finance.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;

public class HttpClientUtils {

    private static final Log log = LogFactory.getLog(HttpClientUtils.class);

    private static final String REQUEST_HEADER = "x-forwarded-for";

    private static final int SOCKET_TIMEOUT = 60000;
    private static final int CONNECTION_TIMEOUT = 60000;
    private static final int MAX_CONN_PER_HOST = 20;
    private static final int MAX_CONN = 100;
    private static final HttpConnectionManager httpClientConnectionManager;

    static {
        httpClientConnectionManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams params = httpClientConnectionManager.getParams();
        params.setConnectionTimeout(CONNECTION_TIMEOUT);
        params.setSoTimeout(SOCKET_TIMEOUT);
        params.setDefaultMaxConnectionsPerHost(MAX_CONN_PER_HOST);
        params.setMaxTotalConnections(MAX_CONN);
    }

    public static String doHttpPostRequest(String url, String ip, Map<String, String> params) throws UnsupportedEncodingException {
        long start = System.currentTimeMillis();
        HttpClient httpClient = new HttpClient(httpClientConnectionManager);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(300000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(300000);
        resetRequestHeader(httpClient, ip);
        PostMethod postMethod = new PostMethod(url);

        String data = "";
        if (params != null && params.size() != 0) {
            data = JSON.toJSONString(params);
        }

        RequestEntity requestEntity = new StringRequestEntity(data, "application/json", "utf-8");
        postMethod.setRequestEntity(requestEntity);
        String response = null;
        try {
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        } catch (IOException e) {
            log.error("请求" + url + "时,发生异常!", e);
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        long end = System.currentTimeMillis();
        log.debug("请求耗时" + (end - start) + "毫秒!");
        return response;
    }

    public static void resetRequestHeader(HttpClient client, String ip) {
        ArrayList<Header> headers = new ArrayList<>();
        headers.add(new Header(REQUEST_HEADER, ip));
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        client.getHostConfiguration().getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    }
}
